//
//  PayOrderViewController.m
//  LiverClient
//
//  Created by dongshangtong on 16/5/10.
//  Copyright © 2016年 朱亚杰. All rights reserved.
//

#import "PayOrderViewController.h"
#import "payHeaderView.h"
#import "PayOrderViewCell.h"
#import "submitView.h"
#import "OrderDetailModel.h"
//支付宝
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "DataSigner.h"
//订单详情界面
#import "YCOrderDetailViewController.h"
//列表界面
#import "YCReadingListViewController.h"
#import "YCNavViewController.h"
#import "YCTabbarViewController.h"

#import "YCMyOrderViewController.h"

@interface PayOrderViewController ()<UITableViewDelegate,UITableViewDataSource,submitViewToComfirmDelegate>

@property (nonatomic,strong )UITableView *tableView;

@property (nonatomic ,strong)NSMutableArray *dataSoure;

@property (nonatomic,strong)Order *ycorder;

@property (nonatomic,assign)NSInteger payType;

@property (nonatomic,strong)NSString *prepay_id;

//支付宝账号
@property (nonatomic ,strong)NSDictionary *zhifubaoDic;


//帐户余额
@property (nonatomic,strong) NSString* balance;



@property (strong, nonatomic) submitView *subView;


//储蓄卡消费返回来 流水号；
@property (nonatomic ,strong)NSString *r_tranno;


@end

@implementation PayOrderViewController
{
    NSDictionary *benzhi;
    NSString* order_id;
    NSString* card_number;
    NSString* order_money;
    NSString* order_name;
    //NSString* available_amount;
    /**代表是否余额不足,YES代表余额不足 NO代表余额足够了*/
    bool balanceFlag;
    /**判断是否具有储值卡,YES代表有 NO代表没有 */
    bool valueCardFlag;
}


-(NSMutableArray *)dataSoure
{
    
    if (!_dataSoure) {
        
        _dataSoure = [NSMutableArray array];
    }
    
    return _dataSoure;
}


-(UITableView *)tableView
{
    
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
        
        self.tableView.dataSource = self;
        
        self.tableView.delegate = self;
        
       // self.tableView.backgroundColor = YCColor(229, 229, 229);
        
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        self.tableView.backgroundColor = [UIColor whiteColor];
        
        [self.view addSubview:self.tableView];
        
    }
    
    
    return _tableView;
    
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
   
    
    self.navigationItem.title = @"支付订单";

    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"PayOrderViewCell" bundle:nil] forCellReuseIdentifier:@"PayOrderViewCell"];
    //默认选中第一支付方式
    self.payType = 0;
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
    
}


- (void)wxPayStatu:(NSNotification*)noti{
    
    if ([noti.object isEqualToString:@"0"])
    {
        [self sendPayStatus:1];
    }
    
}

- (void)alipayStatus:(NSNotification*)noti{
    
    if (noti.object && [noti.object isEqualToString:@"9000"]) {
        [self presentSuccessTips:@"支付成功！"];
        [self sendPayStatus:1];
    }
    else
    {
        [self presentSuccessTips:@"支付失败！"];
        
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //  微信回调的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxPayStatu:) name:@"wxPayStatu" object:nil];
    
    
    //    注册一个通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayStatus:) name:@"alipayStatus" object:nil];
    
    
    
    //1.每次进来需要以前所有数据移除
    [self.dataSoure removeAllObjects];
    
    
    //2.再添加数据
    [self createData];
    
    
    
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    //    移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wxPayStatu" object:nil];
    
    //    移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"alipayStatus" object:nil];
}



-(void)createData{
    
    NSDictionary *weixin = @{
                             @"payName":@"微信支付",
                             @"paySubtitle":@"推荐微信用户使用",
                             @"payImg":@"wechat"
                             };
    
    NSDictionary *zhibao = @{
                             @"payName":@"支付宝",
                             @"paySubtitle":@"推荐支付宝用户使用",
                             @"payImg":@"zfb_pic"
                             };
    
    [self.dataSoure addObject:weixin];
    [self.dataSoure addObject:zhibao];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataSoure.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    PayOrderViewCell  *cell = [PayOrderViewCell payOrderViewCellWithTableView:tableView];
    
    cell.payDit = self.dataSoure [indexPath.row];
    
    cell.selectionStyle= UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

-(CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 120;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    payHeaderView *pHead = [[[NSBundle mainBundle] loadNibNamed:@"payHeaderView" owner:nil options:nil]lastObject];
    pHead.headerName.text = self.readingModel.hosName;
    
    pHead.orderMoney = self.readingModel.payMoney;
    
    return pHead;
    
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    submitView *subView = [[[NSBundle mainBundle] loadNibNamed:@"submitView" owner:nil options:nil]lastObject];
    
    subView.delegate = self;
    
    self.subView = subView;
    
    return subView;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 420;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{
    self.payType = indexPath.row;
    
    
}


/*
 *
 *  提交支付
 *
 */
-(void)submitViewToComfirm{
    
    //提前确定这条订单没有被取消
    [self judgeOrderYesOrNo];
    
}


/*
判断是否订单还存在
 
 */
-(void)judgeOrderYesOrNo
{
    NSString *url = orderinfoUrl;
    NSDictionary *params =@{
                            @"order_id":self.readingModel.orderId,
                            };
    
    [DownloadData post:url params:params success:^(NSDictionary* json) {
        
        //待付款状态下才能去支付
        if([json[@"order_status"] isEqualToString:@"0"])
        {
            [self payOrder];
        }
        else{
            [[UIApplication sharedApplication].keyWindow presentFailureTips:@"订单异常不能支付"];
        }
        
    } failure:^(NSError *error) {
        
      
    }];
}
-(void)payOrder
{
    if (self.payType ==0) {
        
       self.subView.confirmBtn.uxy_acceptEventInterval = 0.1f;
        
        if (self.prepay_id)//已经有预付订单
        {
//            [[UIApplication sharedApplication].keyWindow presentLoadingTips:nil];
            NSDictionary *dic = [wxpayTool createWXRequestParameterWith:self.prepay_id];
            [WXApiRequestHandler jumpToBizPay:dic];
        }
        else
        {
            [self getPrepayIdWithOrderid:self.readingModel.orderId];
        }
    }else if (self.payType ==1){
     
        //支付宝暂时不用
        self.subView.confirmBtn.uxy_acceptEventInterval = 10.f;
        
        if (self.zhifubaoDic) {
            [self payToZhiFuBao];
            
        }else{
            
            [self requestpayToZhiFuBao];
        }
    }
}


/**
 * @brief 预支付交易单号
 *

 *
 * @exception NSException
 */
-(void)getPrepayIdWithOrderid:(NSString *)orderID

{
    NSString *url = unifiedOrderUrl;
    
    [self presentLoadingTips:nil];
    NSDictionary *params =@{@"appid":AppID,
                            @"mchid":MchID,
                            @"ip":[NSString getIPAddress:NO],
                            @"orderid":orderID,
                            };
    
    [DownloadData post:url params:params success:^(id json) {
        
        [self dismissTips];
        
        self.prepay_id=json[@"prepay_id"];
        
        if (self.prepay_id.length!=0) {
            [self dismissTips];
            NSDictionary *dic = [wxpayTool createWXRequestParameterWith:self.prepay_id];
            [WXApiRequestHandler jumpToBizPay:dic];
            
            
        }else{
            [self presentFailureTips:@"获取预付单号失败!请选择其他支付方式!"];
        }
    
    } failure:^(NSError *error) {
        
        [self presentFailureTips:@"获取预付单号失败!!请选择其他支付方式!"];
        
        
    }];
    
}


#pragma mark--------请求支付宝账号
-(void)requestpayToZhiFuBao
{

    NSString *mobile = [YCUserTool sharedTools].linkMobile;
    
    //加盐
    NSString *zhanghao = [NSString stringWithFormat:@"YcXh2016%@@)!$",mobile];
    
    //MD5 加密
    NSString  *zhanghaoMD5 = [zhanghao yc_md5];
    
    NSString *url = zhifubaoZhanghaoUrl;
    
    NSDictionary *parms = @{
                            @"Mobile":mobile,
                            @"KeyValue":zhanghaoMD5
                            };
        
    
    [[UIApplication sharedApplication].keyWindow presentLoadingTips:nil];
    [DownloadData post:url params:parms success:^(id json) {
        
        NSString * PrivKey  = json[@"Md5Key"];
        
        if (PrivKey.length != 0){
            
            [[UIApplication sharedApplication].keyWindow dismissTips];
            self.zhifubaoDic = json;
            
            //支付宝
            [self payToZhiFuBao];
            
        }else{
            [[UIApplication sharedApplication].keyWindow dismissTips];
            [[UIApplication sharedApplication].keyWindow presentFailureTips:@"请求失败!请选择其他支付方式!"];
        }
    } failure:^(NSError *error) {
        
        [[UIApplication sharedApplication].keyWindow dismissTips];
        [[UIApplication sharedApplication].keyWindow presentFailureTips:@"请求失败!请选择其他支付方式!"];
        
    }];
    
    
    
    
    
    
}




/**
 *  选择支付宝支付
 */
-(void)payToZhiFuBao
{
    
    self.ycorder = [[Order alloc] init];
    
    
    self.ycorder.tradeNO =self.readingModel.orderId;
    self.ycorder.productName = self.readingModel.hosName;
    self.ycorder.productDescription = self.readingModel.hosName;
    
    
//    self.ycorder.partner = PartnerID;
//    self.ycorder.seller = SellerID;
    
        self.ycorder.partner = self.zhifubaoDic[@"PartnerID"];
        self.ycorder.seller = self.zhifubaoDic[@"SellerID"];
       // self.ycorder.amount = @"0.01";
        self.ycorder.amount =self.readingModel.payMoney;
    //[self.orderModel.agio description];
    
    
    self.ycorder.notifyURL =  @"http://corp.yk2020.com/"; //回调URL
    
    self.ycorder.service = @"mobile.securitypay.pay";
    self.ycorder.paymentType = @"1";
    self.ycorder.inputCharset = @"utf-8";
    self.ycorder.itBPay = @"30m";
    self.ycorder.showUrl = @"m.alipay.com";
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = ALIPAY_SCHEME;
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [self.ycorder description];
    
    // 2.签名加密
   // id<DataSigner> signer = CreateRSADataSigner(PartnerPrivKey);
    id<DataSigner> signer = CreateRSADataSigner(self.zhifubaoDic[@"PartnerPrivKey"]);

    // 签名信息 == signedString
    NSString *signedString = [signer signString:[orderSpec description]];
    
    // 3.利用订单信息、签名信息、签名类型生成一个订单字符串
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        

        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            
            NSString *zhifuresult =resultDic[@"resultStatus"];

            if ([zhifuresult isEqualToString:@"9000"]) {
                [self sendPayStatus:1];
                
                
            }else{
                
                //支付失败
                
                //[self sendPayStatus:2];
                
                
            }
            
            //NSLog(@"1213");
        }];
        
    }
    
    
}

//支付成功 更新订单状态
-(void)sendPayStatus:(NSInteger)status
{
    
    
    NSString *url = success_onlinepayUrl;
    
 
    
    NSDictionary *params =@{
                            @"order_id":self.readingModel.orderId,
                            @"serial_number":self.readingModel.orderId,//微信和支付宝没有流水号,暂时订单号代替。
                            @"order_status":@(status),
                            @"yw_id":yw_id
                            };
    [DownloadData post:url params:params success:^(id json) {
        [self dismissTips];
        
        NSString *orderid =json[@"error_code"];
        
        if ( [orderid isEqualToString:@"ok"] || [orderid isEqualToString:@"00042"]) {
            
            
            if (status ==2) {
                [self presentFailureTips:@"支付失败！"];
                


            }else{
                
                [self presentSuccessTips:@"订单支付成功"];
                
                //返回获取到tabbar控制器
                [self.navigationController popToRootViewControllerAnimated:NO];
                //获取到tabbar控制器
                YCTabbarViewController *tabbarVc = (YCTabbarViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                
                YCNavViewController *rootNav = (YCNavViewController *)tabbarVc.childViewControllers[tabbarVc.selectedIndex];
                
                UIViewController *currentVc = rootNav.childViewControllers[0];
                
                YCMyOrderViewController *listVc = [[YCMyOrderViewController alloc]init];
 
                [currentVc.navigationController pushViewController:listVc animated:NO];
                
            }
            
        }else{
            
            [self presentSuccessTips:@"支付失败！"];
        }
        
    } failure:^(NSError *error) {
        
        
        [self dismissTips];
        
        [self presentFailureTips:@"支付失败"];
        
    }];
  
}


@end
